package com.tool_stdy.utils.guava;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class GuavaCatchCacheLoader {

    private  static LoadingCache<String, String> loadc = null;
    static{
        loadc=CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<String, String>(){
            @Override
            public String load(String key) throws Exception {
                return getDataFromDB(key);
            }
        });
    }
    
    public static  String getDataFromDB(String name){
        System.out.println(name+" get  from db doing...");
        return "hello "+name;
    }
    public static void main(String[] args) throws Exception {
        //loadc.put("lisi", "i am lisi");
        System.out.println("第一次执行 "+loadc.get("lisi"));//第一次访问catch中没有 执行load方法
        Thread.sleep(3000);
        System.out.println("第二次执行 "+loadc.get("lisi"));//第二次访问catch中有 直接获取
        Thread.sleep(2000);
//      loadc.put("lisi", "ni hao a");
       // loadc.get("lisi");
        Thread.sleep(3000);
        System.out.println("第三次执行超出时间限制,再次数据源获取"+loadc.get("lisi"));//第三次访问catch中是否超时
        Thread.sleep(5000);
        System.out.println(loadc.get("wangwu"));
    }
}
